package com.ejlchina.common.oss;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;


/**
 * 
 * 阿里云对象存储管理器
 * 
 * @author Troy.Zhou
 *
 */

public class AliyunOssManager extends AbstractOssManager implements InitializingBean, DisposableBean {

	
	private String accessKeyId;
	
	private String accessKeySecret;
	
	private String bucketName;
	
	private OSSClient client;
	
	
	@Override
	public void afterPropertiesSet() throws Exception {
		client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
	}
	
	
	@Override
	public String upload(String key, File file) {
		String extension = getFileExtension(file.getName());
		String contentType = getContentType(extension);
		try {
			return upload(key, contentType, extension, new FileInputStream(file));
		} catch (FileNotFoundException e) {
			throw new RuntimeException("上传出错：", e);
		}
	}

	
	@Override
	public String upload(String key, String contentType, InputStream inputStream) {
		return upload(key, contentType, toExtension(contentType), inputStream);
	}

	
	private String upload(String key, String contentType, String extension, InputStream inputStream) {
		try {
			client.putObject(bucketName, key, new ByteArrayInputStream(new byte[0]));
			OSSObject object = client.getObject(bucketName, key);
			object.getObjectContent().close();
		} catch (Exception e) {
			throw new RuntimeException("创建目录【" + key + "】异常：", e);
		}
		try {
			Long fileSize = (long) inputStream.available();
			if(fileSize > maxSize) {
				inputStream.close();
				throw new RuntimeException("上传的文件过大：" + fileSize + "，最大只允许：" + maxSize);
			}
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentLength(inputStream.available());
			metadata.setCacheControl("no-cache");
			metadata.setHeader("Pragma", "no-cache");
			metadata.setContentEncoding("utf-8");
			String fileName = System.currentTimeMillis()
					+ RandomStringUtils.random(5, true, true) + extension;
			metadata.setContentType(contentType);
			metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
			String fileKey = key + fileName;
			client.putObject(bucketName, fileKey, inputStream, metadata);
			return resolveFileAccessUrl(fileKey);
		} catch (Exception e) {
			throw new RuntimeException("上传出现异常：", e);
		}
	}

	@Override
	public boolean delete(String fileUrl) {
		String fileKey = resolveFileKey(fileUrl);
		if (fileKey != null) {
			client.deleteObject(bucketName, fileKey);
			return true;
		}
		return false;
	}

	@Override
	public void destroy() {
		client.shutdown();
	}
	
	
	@Override
	protected String getBaseAccessUrl(String protocol, String host) {
		return protocol + bucketName + "." + host + "/";
	}
	
	
	public String getAccessKeyId() {
		return accessKeyId;
	}

	public void setAccessKeyId(String accessKeyId) {
		this.accessKeyId = accessKeyId;
	}

	public String getAccessKeySecret() {
		return accessKeySecret;
	}

	public void setAccessKeySecret(String accessKeySecret) {
		this.accessKeySecret = accessKeySecret;
	}

	public String getBucketName() {
		return bucketName;
	}

	public void setBucketName(String bucketName) {
		this.bucketName = bucketName;
	}


}
